package com.peanut.baby.mvp.bind;

import android.app.Activity;

import com.peanut.baby.InitManager;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseResponse;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.User;
import com.peanut.devlibrary.util.SmsUtil;
import com.tencent.mars.xlog.Log;

import cn.nekocode.rxlifecycle.RxLifecycle;
import io.reactivex.Observable;

/**
 * Created by anonymouslystudio on 2017/7/11.
 */

public class BindMobilePresenter implements BindContract.Presenter,SmsUtil.OnSmsStatusChangeListener{
    private static final String TAG = BindMobilePresenter.class.getSimpleName();
    protected BindContract.View view;
    private Runnable countRunnable;
    private Thread  countThread;
    private Activity    activity;
    public BindMobilePresenter(BindContract.View view,Activity activity){
        this.view = view;
        this.activity = activity;
    }


    @Override
    public void getVCode(String mobile) {
        SmsUtil.getInstance().setOnSmsStatusChangeListener(this);
        SmsUtil.getInstance().registReceiver();
        SmsUtil.getInstance().getVCode(mobile);
    }

    @Override
    public void submitBind(String mobile, String code) {
        Log.d(TAG,"check sms success");
        Observable observable = RetrofitClient.getInstance().bindMobile(InitManager.getInstance().getUserId(),mobile,code);
        observable.compose(BaseScheduler.<BaseResponse<User>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<User>() {
            @Override
            protected void onHandleSuccess(User o) {
                InitManager.getInstance().setUser(o);
                view.onBindSuccess();
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onBindFailed(code,msg);
            }

        });
    }

    @Override
    public void onRequestSmsFinished(boolean success, String failReason) {

        if(success){
            view.startCountDown();
            startCountDown();
        }else{
            view.onRequestSMSCodeFailed("请求验证码失败 "+failReason);
        }
    }

    /**
     * call when get code request success
     */
    private void startCountDown(){
        stopThreadAndRunnable();
        countRunnable = new CountingRunnable();
        countThread = new Thread(countRunnable);
        countThread.start();
    }

    /**
     * 计数器
     */
    class CountingRunnable implements Runnable{
        int current = 60;
        public CountingRunnable() {
        }

        @Override
        public void run() {
            view.startCountDown();
            while(current > 0){
                view.onCountDown(current);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
                current --;
            }
            view.onCountComplete();

        }
    }



    private void stopThreadAndRunnable(){

        try {
            if(countThread != null){
//                countThread.stop();
            }
            countThread = null;
            if(countRunnable != null){
                countRunnable = null;
            }
        } catch (Exception e) {

        } finally {
            countRunnable = null;
            countThread = null;
        }
    }


    public void onDestory(){
        stopThreadAndRunnable();
        SmsUtil.getInstance().removeReceiver();

    }
}
